package com.atguigu.gulimall.ware.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;
/**
 * 自定义 MQ 配置类
 * durable: 是否持久化, exclusive: 是否排他性, autoDelete: 是否自动删除, routingKey: 路由键
 * 如果配置发生改变，重新运行不会覆盖原来的，只能删了，重新生成
 */
@Configuration
public class MyRabbitConfig {
    /**
     * 配置 消息转换器 放到容器中
     */
    @Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();  //Json 消息转换器
    }

    /**
     * 消费者监听消息, 要有消费者才能创建出交换机和队列
     */
    //@RabbitListener(queues = "stock.dead.queue")
    //public void handle(Message message){

    //}

    /**
     * Topic 交换机 (要绑定两个队列，所以用 Topic 交换机)
     */
    @Bean
    public Exchange stockEventExchange() {
        return new TopicExchange("stock-event-exchange", true, false);
    }

    /**
     * 死信队列
     */
    @Bean
    public Queue stockDeadStockQueue() {
        return new Queue("stock.dead.queue", true, false, false);
    }

    /**
     * 延时队列
     */
    @Bean
    public Queue stockDelayQueue() {
        Map<String, Object> arguments = new HashMap<>();
        arguments.put("x-dead-letter-exchange", "stock-event-exchange");    //自定义死信放到哪个交换机
        arguments.put("x-dead-letter-routing-key", "stock.dead.stock");    //死信路由键
        arguments.put("x-message-ttl", 120000);    //消息过期时间，毫秒，两分钟
        return new Queue("stock.delay.queue", true, false, false, arguments);
    }

    /**
     * 绑定死信队列 到 交换机
     */
    @Bean
    public Binding stockDeadStockBinding() {
        return new Binding("stock.dead.queue", Binding.DestinationType.QUEUE, "stock-event-exchange",
                "stock.dead.stock", new HashMap<>());
    }

    /**
     * 绑定延时队列 到 交换机
     */
    @Bean
    public Binding stockDelayBinding() {
        return new Binding("stock.delay.queue", Binding.DestinationType.QUEUE, "stock-event-exchange",
                "stock.delay.stock", new HashMap<>());
    }
}
